<template>
  <view class="create-group">
    <!-- 群组基本信息 -->
    <view class="group-info-form">
      <view class="form-item">
        <text class="form-label">群组头像</text>
        <view class="avatar-uploader" @click="chooseAvatar">
          <image
            v-if="groupInfo.avatar"
            class="group-avatar"
            :src="groupInfo.avatar"
            mode="aspectFill"
          />
          <view v-else class="avatar-placeholder">
            <wd-icon name="camera" size="24px" color="#999" />
            <text>上传头像</text>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">群组名称</text>
        <input
          v-model="groupInfo.name"
          class="form-input"
          placeholder="请输入群组名称"
          maxlength="20"
        />
        <text class="input-counter">{{ groupInfo.name.length }}/20</text>
      </view>

      <view class="form-item">
        <text class="form-label">群组简介</text>
        <textarea
          v-model="groupInfo.description"
          class="form-textarea"
          placeholder="请输入群组简介"
          maxlength="100"
          auto-height
        />
        <text class="input-counter">{{ groupInfo.description.length }}/100</text>
      </view>
    </view>

    <!-- 添加成员 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">添加成员</text>
        <text class="member-count">已选择 {{ selectedContacts.length }} 人</text>
      </view>

      <!-- 搜索框 -->
      <view class="search-box">
        <view class="search-input-box">
          <wd-icon name="search" size="16px" color="#999" class="search-icon" />
          <input
            v-model="searchKeyword"
            class="search-input"
            placeholder="搜索宗亲"
            @input="handleSearch"
          />
        </view>
      </view>

      <!-- 已选成员列表 -->
      <view v-if="selectedContacts.length > 0" class="selected-members">
        <scroll-view scroll-x class="selected-scroll">
          <view class="selected-list">
            <view
              v-for="(contact, index) in selectedContacts"
              :key="contact.id"
              class="selected-item"
            >
              <image class="selected-avatar" :src="contact.avatar" mode="aspectFill" />
              <text class="selected-name">{{ contact.name }}</text>
              <view class="remove-btn" @click.stop="removeSelectedContact(index)">
                <wd-icon name="close" size="12px" color="#fff" />
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 联系人列表 -->
      <view class="contacts-wrapper">
        <view v-if="searchKeyword && filteredContacts.length > 0" class="contact-list">
          <view
            v-for="contact in filteredContacts"
            :key="contact.id"
            class="contact-item"
            @click="toggleSelectContact(contact)"
          >
            <view class="contact-info">
              <image class="contact-avatar" :src="contact.avatar" mode="aspectFill" />
              <text class="contact-name">{{ contact.name }}</text>
            </view>
            <checkbox
              class="contact-checkbox"
              :checked="isContactSelected(contact)"
              color="#3B8DFF"
            />
          </view>
        </view>

        <view v-else-if="searchKeyword && filteredContacts.length === 0" class="empty-result">
          <text>未找到匹配的联系人</text>
        </view>

        <view v-else>
          <view v-for="(group, index) in contactGroups" :key="index" class="contact-group">
            <view class="group-title">{{ group.letter }}</view>
            <view class="contact-list">
              <view
                v-for="contact in group.contacts"
                :key="contact.id"
                class="contact-item"
                @click="toggleSelectContact(contact)"
              >
                <view class="contact-info">
                  <image class="contact-avatar" :src="contact.avatar" mode="aspectFill" />
                  <text class="contact-name">{{ contact.name }}</text>
                </view>
                <checkbox
                  class="contact-checkbox"
                  :checked="isContactSelected(contact)"
                  color="#3B8DFF"
                />
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <!-- <view class="footer">
      <button
        class="create-btn"
        :class="{ 'btn-disabled': !isFormValid }"
        @click="handleCreateGroup"
      >
        创建群组
      </button>
    </view> -->
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";

// 定义联系人类型
interface Contact {
  id: string;
  name: string;
  avatar: string;
  relation: string;
}

// 定义联系人分组类型
interface ContactGroup {
  letter: string;
  contacts: Contact[];
}

// 定义群组信息类型
interface GroupInfo {
  name: string;
  avatar: string;
  description: string;
}

// 设置页面标题
uni.setNavigationBarTitle({
  title: "创建群组",
});

// 群组信息
const groupInfo = ref<GroupInfo>({
  name: "",
  avatar: "",
  description: "",
});

// 搜索关键词
const searchKeyword = ref("");

// 选择的联系人
const selectedContacts = ref<Contact[]>([]);

// 所有联系人（按字母分组）
const contactGroups = ref<ContactGroup[]>([
  {
    letter: "A",
    contacts: [{ id: "a1", name: "阿强", avatar: "/static/avatar.png", relation: "五代孙" }],
  },
  {
    letter: "B",
    contacts: [{ id: "b1", name: "宝宝", avatar: "/static/avatar.png", relation: "七代孙女" }],
  },
  {
    letter: "L",
    contacts: [
      { id: "l1", name: "李家大姐", avatar: "/static/avatar.png", relation: "四代孙女" },
      { id: "l2", name: "李家三叔", avatar: "/static/avatar.png", relation: "三代孙" },
      { id: "l3", name: "李家族长", avatar: "/static/avatar.png", relation: "二代孙" },
      { id: "l4", name: "李二狗", avatar: "/static/avatar.png", relation: "六代孙" },
    ],
  },
  {
    letter: "Z",
    contacts: [{ id: "z1", name: "志强", avatar: "/static/avatar.png", relation: "五代孙" }],
  },
]);

// 根据搜索关键词过滤联系人
const filteredContacts = computed(() => {
  if (!searchKeyword.value) return [];

  const keyword = searchKeyword.value.toLowerCase();
  const results: Contact[] = [];

  contactGroups.value.forEach((group) => {
    group.contacts.forEach((contact) => {
      if (contact.name.toLowerCase().includes(keyword)) {
        results.push(contact);
      }
    });
  });

  return results;
});

// 表单是否有效
const isFormValid = computed(() => {
  return groupInfo.value.name.trim() !== "" && selectedContacts.value.length >= 2;
});

// 选择群组头像
function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      groupInfo.value.avatar = res.tempFilePaths[0];
    },
  });
}

// 处理搜索
function handleSearch() {
  // 搜索逻辑在 computed 中处理
}

// 判断联系人是否被选中
function isContactSelected(contact: Contact): boolean {
  return selectedContacts.value.some((item) => item.id === contact.id);
}

// 切换选择联系人
function toggleSelectContact(contact: Contact) {
  const index = selectedContacts.value.findIndex((item) => item.id === contact.id);

  if (index > -1) {
    // 已选中，取消选择
    selectedContacts.value.splice(index, 1);
  } else {
    // 未选中，添加选择
    selectedContacts.value.push(contact);
  }
}

// 移除已选联系人
function removeSelectedContact(index: number) {
  selectedContacts.value.splice(index, 1);
}

// 创建群组
// function handleCreateGroup() {
//   if (!isFormValid.value) {
//     if (groupInfo.value.name.trim() === "") {
//       uni.showToast({
//         title: "请输入群组名称",
//         icon: "none",
//       });
//     } else if (selectedContacts.value.length < 2) {
//       uni.showToast({
//         title: "请至少选择2名成员",
//         icon: "none",
//       });
//     }
//     return;
//   }

  // 模拟创建群组
//   setTimeout(() => {
//     uni.showLoading({ title: "创建中..." });

//     setTimeout(() => {
//       uni.hideLoading();

//       // 创建成功，跳转到群聊页面
//       const groupId = Date.now().toString();

//       uni.showToast({
//         title: "创建成功",
//         icon: "success",
//         success: () => {
//           // 延迟跳转，让用户看到成功提示
//           setTimeout(() => {
//             uni.navigateTo({
//               url: `/pages/chat/detail?id=${groupId}&name=${encodeURIComponent(groupInfo.value.name)}&isGroup=true`,
//             });
//           }, 1500);
//         },
//       });
//     }, 1500);
//   }, 100);
// }
</script>

<style lang="scss">
.create-group {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.group-info-form {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
  position: relative;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.avatar-uploader {
  width: 150rpx;
  height: 150rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.group-avatar {
  width: 150rpx;
  height: 150rpx;
}

.avatar-placeholder {
  width: 150rpx;
  height: 150rpx;
  background-color: #f0f0f0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  text {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }
}

.form-input {
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.form-textarea {
  width: 100%;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  min-height: 120rpx;
}

.input-counter {
  position: absolute;
  bottom: 10rpx;
  right: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.section {
  background-color: #fff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
}

.member-count {
  font-size: 24rpx;
  color: #999;
}

.search-box {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-input-box {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  height: 72rpx;
  border-radius: 36rpx;
  padding: 0 30rpx;
}

.search-icon {
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  line-height: 72rpx;
  font-size: 28rpx;
  background-color: transparent;
}

.selected-members {
  max-height: 180rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.selected-scroll {
  white-space: nowrap;
}

.selected-list {
  display: inline-flex;
  padding: 0 30rpx;
}

.selected-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  margin-right: 30rpx;
  width: 100rpx;
}

.selected-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
}

.selected-name {
  width: 100%;
  text-align: center;
  font-size: 24rpx;
  color: #333;
  margin-top: 10rpx;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.remove-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  background-color: #ff4d4f;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contacts-wrapper {
  max-height: 750rpx;
  overflow-y: auto;
}

.contact-group {
  margin-bottom: 20rpx;
}

.group-title {
  padding: 10rpx 30rpx;
  background-color: #f8f8f8;
  font-size: 24rpx;
  color: #999;
}

.contact-list {
  background-color: #fff;
}

.contact-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.contact-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.contact-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.contact-name {
  font-size: 28rpx;
  color: #333;
}

.contact-checkbox {
  transform: scale(0.8);
}

.empty-result {
  display: flex;
  justify-content: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -1rpx 8rpx rgba(0, 0, 0, 0.05);
}

.create-btn {
  background-color: #3b8dff;
  color: #fff;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.btn-disabled {
  background-color: #cccccc;
  color: #ffffff;
}
</style>
